package cn.edu.sgu.www.mhxysy.config;

import cn.edu.sgu.www.mhxysy.quartz.TemporaryFileCleanJob;
import com.alibaba.druid.pool.DruidDataSource;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.quartz.QuartzDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Quartz配置类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Configuration
public class QuartzConfig {

    private final DataSourceProperties dataSourceProperties;

    @Autowired
    public QuartzConfig(DataSourceProperties dataSourceProperties) {
        this.dataSourceProperties = dataSourceProperties;
    }

    /**
     * 定义Quartz任务详情
     * @return JobDetail
     */
    @Bean
    public JobDetail jobDetail() {
        Class<TemporaryFileCleanJob> jobClass = TemporaryFileCleanJob.class;

        JobBuilder jobBuilder = JobBuilder.newJob(jobClass);

        jobBuilder.withIdentity(jobClass.getSimpleName()); // 任务名称
        jobBuilder.storeDurably();

        return jobBuilder.build();
    }

    /**
     * 定义Quartz任务触发器
     * @return Trigger
     */
    @Bean
    public Trigger trigger(JobDetail jobDetail) {
        // 定义Cron表达式：每3小时触发一次定时任务
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0 0 3/3 * * ?");

        return TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity("trigger")            // 触发器名称
                .withSchedule(cronScheduleBuilder)  // Cron表达式
                .build();
    }

    /**
     * 定义Quartz数据源
     * @return DataSource
     */
    @Bean
    @QuartzDataSource
    public DataSource quartzDataSource() {
        DruidDataSource dataSource = new DruidDataSource();

        String url = dataSourceProperties.getUrl();
        int index = url.lastIndexOf("/");

        dataSource.setUrl(url.substring(0, index + 1) + "quartz_db");
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());

        return dataSource;
    }

}